﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace FightLand_Sever.Core
{
    class GameListener
    {
        HttpListener listener;

        //资源根目录
#if DEBUG
        static string ProjectsDir = @"D:\Desktop\Work\ServerOrWeb\FightLandlord\Web\dist";
        static string RootDir = @"D:\Desktop\Work\ServerOrWeb\FightLandlord\Web";

#else
        static string ProjectsDir = System.IO.Directory.GetCurrentDirectory() + "\\Web\\dist";
        static string RootDir = System.IO.Directory.GetCurrentDirectory() + "\\Web";
#endif
        public GameListener()
        {
            HttpListener listener = new HttpListener();
            listener.Prefixes.Add(string.Format("http://{0}:8769", Server.IP));
            listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
            this.listener = listener;
        }

        //异步递归监听http请求
        private async void Listen()
        {
            var ctx = await this.listener.GetContextAsync();
            ThreadPool.QueueUserWorkItem(RequestHandle, ctx);
            Listen();
        }

        private void RequestHandle(object state)
        {
            HttpListenerContext ctx = (HttpListenerContext)state;
            var rq = ctx.Request;
            var rp = ctx.Response;
            if (StaticFileHandler(ctx))
            {
                rp.Close();
                return;
            }
        }

        //静态资源处理
        private static bool StaticFileHandler(HttpListenerContext ctx)
        {
            var rq = ctx.Request;
            var rp = ctx.Response;
            if (rq.HttpMethod != "GET") return false;
            var stream = rp.OutputStream;
            string path = rq.Url.AbsolutePath; //请求路径
            path = path.Replace("/", "\\");   //格式化请求路径
            //如果为静态资源则返回到根目录寻找
            if (path.StartsWith("\\static"))
            {
                var fpath = RootDir + path;
                if (File.Exists(fpath))
                {
                    rp.StatusCode = 200;
                    byte[] by = Tools.GetFileData(fpath);
                    rp.ContentType = MimeMapping.GetMimeMapping(fpath) + ";charset=UTF-8";
                    rp.ContentLength64 = by.Length;
                    rp.OutputStream.Write(by, 0, by.Length);
                }
                return true;
            }
            return false;
        }

        public void Run()
        {

        }
    }
}
